package com.yopuo.port.facade;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yopuo.common.constant.Constants;
import com.yopuo.common.core.domain.entity.SysMenu;
import com.yopuo.common.core.domain.entity.SysRole;
import com.yopuo.common.core.domain.entity.SysUser;
import com.yopuo.common.exception.msg.CdPortMsg;
import com.yopuo.common.utils.SecurityUtils;
import com.yopuo.common.utils.bean.BeanUtils;
import com.yopuo.port.vo.CloudDiskReqVo;
import com.yopuo.system.domain.SysMenuCdisk;
import com.yopuo.system.service.ISysMenuCdiskService;
import com.yopuo.system.service.ISysMenuService;
import com.yopuo.system.service.ISysRoleService;
import com.yopuo.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 菜单 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysMenuCdiskFacade
{
    /**
     * 默认创建人
     */
    private static final String CREATE_BY = "admin";

    @Resource
    private ISysUserService userService;
    @Resource
    private ISysMenuCdiskService menuCdiskService;
    @Resource
    private ISysMenuService menuService;
    @Resource
    private ISysRoleService roleService;

    /**
     * 查询用户是否为管理员
     * @param cloudDiskReqVo 云盘参数
     * @return String
     * @author zzh
     */
    public String doQueryUserRole(CloudDiskReqVo cloudDiskReqVo) {
        //当前默认一个云盘用户只有一个角色
        SysUser user = new SysUser();
        user.setRemark(cloudDiskReqVo.getUserId().toString());
        List<SysUser> sysUsers = userService.selectUserList(user);
        if (CollectionUtils.isEmpty(sysUsers)){
            throw new RuntimeException(CdPortMsg.USER_NON_EXIST);
        }
        List<SysRole> sysRoles = roleService.selectRolesByUserId(sysUsers.get(0).getUserId());
        //0管理员账户  1普通账户
        return sysRoles.get(0).getRoleKey().contains("admin") ? Constants.ZERO : Constants.ONE;
    }

    /**
     * 删除权限菜单
     * @param cloudDiskReqVo 云盘参数
     * @author zzh
     */
    public void doDeleteMenu(CloudDiskReqVo cloudDiskReqVo) {
        SysMenuCdisk menuCdisk = new SysMenuCdisk();
        BeanUtils.copyProperties(cloudDiskReqVo, menuCdisk);
        QueryWrapper<SysMenuCdisk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("folder_id", menuCdisk.getFolderId());
        queryWrapper.eq("folder_parent_id", menuCdisk.getFolderParentId());
        //删除云盘菜单
        boolean remove = menuCdiskService.remove(queryWrapper);
        if (remove){
            //删除权限菜单
            SysMenu sysMenu = new SysMenu();
            sysMenu.setRemark(menuCdisk.getFolderId().toString());
            List<Long> menuIds = menuService.deleteMenuByMenu(sysMenu);
            //删除角色菜单关系
            if (!CollectionUtils.isEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    roleService.deleteRoleMenu(menuId);
                }
            }
        }
    }

    /**
     * 查询权限菜单
     * @param cloudDiskReqVo 云盘参数
     * @return String
     * @author zzh
     */
    public String doQueryUserFile(CloudDiskReqVo cloudDiskReqVo) {
        SysMenuCdisk menuCdisk = new SysMenuCdisk();
        BeanUtils.copyProperties(cloudDiskReqVo, menuCdisk);
        SysUser user = new SysUser();
        user.setRemark(cloudDiskReqVo.getUserId().toString());
        List<SysUser> sysUsers = userService.selectUserList(user);
        if (CollectionUtils.isEmpty(sysUsers)){
            throw new RuntimeException(CdPortMsg.USER_NON_EXIST);
        }
        Long userId = sysUsers.get(0).getUserId();
        List<SysMenuCdisk> menuCdisks = menuCdiskService.selectPanMenu(userId, menuCdisk);
        return JSONObject.toJSONString(menuCdisks);
    }

    /**
     * 同步用户（新增、编辑）
     * @param cloudDiskReqVo 云盘参数
     * @author zzh
     */
    public void doSyncUser(CloudDiskReqVo cloudDiskReqVo) {
        SysUser user = new SysUser();
        user.setRemark(cloudDiskReqVo.getUserId().toString());
        user.setUserName(cloudDiskReqVo.getUserName());
        List<SysUser> sysUsers = userService.selectUserList(user);
        //新增或更新
        if (CollectionUtils.isEmpty(sysUsers)){
            user.setCreateBy(CREATE_BY);
            user.setPassword(SecurityUtils.encryptPassword(cloudDiskReqVo.getPassWord()));
            user.setNickName(cloudDiskReqVo.getUserName());
            user.setDelFlag(Constants.SUCCESS);
            user.setStatus(Constants.SUCCESS);
            userService.insertUser(user);
        }else {
            user.setUserId(sysUsers.get(0).getUserId());
            userService.updateUser(user);
        }
    }

    /**
     * 同步菜单（新增、编辑、移动、复制）
     * @param cloudDiskReqVo 云盘参数
     * @author zzh
     */
    public void doSyncMenu(CloudDiskReqVo cloudDiskReqVo) {
        SysMenuCdisk menuCdisk = new SysMenuCdisk();
        BeanUtils.copyProperties(cloudDiskReqVo, menuCdisk);
        QueryWrapper<SysMenuCdisk> wrapper = new QueryWrapper<>();
        wrapper.eq("folder_id", menuCdisk.getFolderId());
        List<SysMenuCdisk> menuCdisks = menuCdiskService.list(wrapper);
        //新增,菜单关系表
        if (CollectionUtils.isEmpty(menuCdisks)){
            menuCdiskService.save(menuCdisk);
            menuService.saveOrUpdateMenu(menuCdisk, cloudDiskReqVo.getUserId());
            //更新(同级目录下文件名唯一)
        }else {
            SysMenuCdisk cdiskOld = menuCdisks.get(0);
            menuCdisk.setId(cdiskOld.getId());
            menuCdiskService.updateById(menuCdisk);
            //移动文件，则父级目录需变更
            if (cdiskOld.getFolderId().compareTo(menuCdisk.getFolderParentId()) != 0 ){
                menuService.moveMenu(menuCdisk);
                //更新文件名称
            }else {
                menuService.saveOrUpdateMenu(menuCdisk, null);
            }
        }
    }
}
